<?php

namespace Modules\Queue\Library;

use Modules\Queue\Models\Queue as QueueModel;
use \Exception;
use GuzzleHttp\Client;
use Phalcon\Di;
use Phalcon\Security\Random;

class Queue
{
    public $queueLog = false;

    public $queueId;

    public function __construct()
    {
        $random = new Random();
        $this->queueId = $random->hex(10);
    }

    //添加任务
    public function add($task, $data, $type = 0, $run = true)
    {
        $di = Di::getDefault();
        $taskList = $di->getShared('config')->cache('task');
        if (!isset($taskList[$task])) {
            //echo '队列类型不存在';
            return false;
        }

        $queueModel = new QueueModel();
        $queueModel->type = $type;
        $queueModel->data = $data;
        $queueModel->state = 0;
        $queueModel->created = time();
        $queueModel->changed = 0;
        $queueModel->queueId = null;
        $queueModel->log = [];
        $queueModel->task = $task;
        $queueState = $queueModel->save();
        if ($queueState && $run === true) {
            $this->start();
            return true;
        } elseif ($queueState) {
            return true;
        }
        return false;
    }

    //开始执行任务
    public function start()
    {
        if ($this->isStart() === true) {
            return false;
        }
        $di = Di::getDefault();
        //$scheme = $di->getShared('request')->getServer('REQUEST_SCHEME');
        $host = $di->getShared('request')->getServer('HTTP_HOST');
        $url = $di->getShared('url')->get(['for' => 'queue']);
        $url = 'http://' . $host . $url;
        $client = new Client();
        $client->getAsync($url, [
            'stream' => true,
            'timeout' => 0.001,
        ]);
    }

    //队列是否在运行中
    public function isStart()
    {
        $lockFile = CACHE_DIR . 'queue/lock';
        if (file_exists($lockFile)) {
            return true;
        }
        return false;
    }

    //运行全部任务
    public function run()
    {
        try {
            file_put_contents(CACHE_DIR . 'queue/lock', 'run queue');
            //运行普通任务
            $this->runTask();
            //$this->cycleTasks();
            //运行定时任务
            //$this->runTimeCron();
            if (file_exists(CACHE_DIR . 'queue/lock')) {
                @unlink(CACHE_DIR . 'queue/lock');
            }
            //exit(0);
        } catch (Exception $e) {
            if (file_exists(CACHE_DIR . 'queue/lock')) {
                @unlink(CACHE_DIR . 'queue/lock');
            }
        }
        if (file_exists(CACHE_DIR . 'queue/lock')) {
            @unlink(CACHE_DIR . 'queue/lock');
        }
        exit(0);
    }

    private function runTask()
    {
        $query = [
            'conditions' => [
                'queueId' => ['$ne' => $this->queueId],
            ],
            'sort' => [
                'changed' => 1
            ]
        ];
        $task = QueueModel::findFirst($query);
        while ($task && $task instanceof QueueModel) {
            //执行任务
            $task->queueId = $this->queueId;
            $task->run();
            //unset($task);
            //$task->save();
            //处理执行后
            $task = QueueModel::findFirst($query);
        }
    }

}